<template>
  <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" class="avatar-uploader"
    :show-upload-list="false" :action="apiURL + 'app/file/upload'" :before-upload="beforeUpload" @change="handleChange">
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
    <div v-else>
      <loadingOutlined v-if="loading" />
      <!-- <plus-outlined v-else></plus-outlined> -->
      <PlusOutlined v-else />
      <div class="ant-upload-text">上传</div>
    </div>
  </a-upload>
</template>
<script setup>
import { computed, ref } from 'vue';
import { message } from 'ant-design-vue';
import { useAppConfig } from '@vben/hooks';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

const props = defineProps({
  value: {
    type: String,
    default: '',
  },
});

const emits = defineEmits(['update:value']);

const imageUrl = computed({
  get() {
    return props.value;
  },
  set(val) {
    emits('update:value', val);
  },
});

const fileList = ref([]);
const loading = ref(false);
// const imageUrl = ref('');
const handleChange = (info) => {
  console.log('info', info);

  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.

    imageUrl.value = info.file?.response?.url;
    console.log('上传成功的回调', imageUrl.value);

    loading.value = false;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = (file) => {
  console.log('图片格式', file.type);

  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/jpg';
  if (!isJpgOrPng) {
    message.error('请上传正确的图片格式');
  }
  // const isLt2M = file.size / 1024 / 1024 < 2;
  // if (!isLt2M) {
  //   message.error('Image must smaller than 2MB!');
  // }
  // return isJpgOrPng && isLt2M;
  return isJpgOrPng;
};
</script>
<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
